import {Module, ActionContext} from 'vuex';
import { RootState } from '../root-types';
import {
  getToken, removeToken, setToken
} from '/@ts/hooks/cookie';

import {
  getInfo,
  login,
  logout
} from '/@ts/axios/urlApi/system';
import { LoginState } from '/@ts/types/system';
export const loginModule:Module<LoginState,RootState>= {
    namespaced: true,//namespaced: true 的方式使其成为带命名空间的模块。保证在变量名一样的时候，添加一个父级名拼接。
    state: ():LoginState => ({
      permissions:[],
      isLogin:false,
      token:"",
      roles:[],
      userInfo:{}
    }),
    mutations: {
      SET_PERMISSIONS (state:LoginState,permissions:Array<string>) {
        // 这里的 `state` 对象是模块的局部状态
        state.permissions = permissions
      },
      SET_ROLES (state:LoginState,roles:Array<string>) {
        // 这里的 `state` 对象是模块的局部状态
        state.roles = roles
      },
      SET_TOKEN (state:LoginState,token:string) {
        // 这里的 `state` 对象是模块的局部状态
        state.token = token
      },
      SET_userInfo (state:LoginState,userInfo:any) {
        // 这里的 `state` 对象是模块的局部状态
        state.userInfo = userInfo
      },
      isLogin(state:LoginState){
        if(getToken()){
          state.isLogin=true//登录
        }else{
          state.isLogin=false//登录
        }
    },
   
    },

    actions: {
        // increment (context:ActionContext<LoginState,RootState>) {
        //   context.commit('increment')
        // },
        Login(context:ActionContext<LoginState,RootState>,userInfo:any){
          return new Promise((resolve, reject) => {
            login(userInfo).then((res:any) => {
              setToken(res.token)
              context.commit('SET_TOKEN', res.token)
              resolve(res.token)
            }).catch((error:Error) => {
              reject(error)
            })
          })
        },
        GetInfo(context:ActionContext<LoginState,RootState>){
          return new Promise((resolve, reject) => {
            getInfo().then((res:any) => {
              const user = res.user
              if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
                context.commit('SET_ROLES', res.roles)
                context.commit('SET_PERMISSIONS', res.permissions)
              } else {
                context.commit('SET_ROLES', ['ROLE_DEFAULT'])
              }
              context.commit('SET_userInfo', user)
              resolve(res)
            }).catch((error:Error) => {
              reject(error)
            })
          })
        },
        LogOut(context:ActionContext<LoginState,RootState>){
          return new Promise((resolve, reject) => {
            
            logout().then(() => {
              context.commit('SET_TOKEN', '')
              context.commit('SET_ROLES', [])
              context.commit('SET_PERMISSIONS', [])
              removeToken()
              resolve('')
            }).catch((error:Error) => {
              reject(error)
            })
          })
        }
      }
  }
  